package com.zhuxulin.android.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * 带加载状态的Button 收集与superdata
 * 
 * @author ZhuXulin
 * 
 */
public class LoadButton extends LinearLayout implements OnClickListener {
	private static String TAG = LoadButton.class.getSimpleName();
	/** 利用此NameSpace 配置的时候可以直接使用名字，而不用导入名字空间，不需要额外XML的配置，就可以在我们的VIEW文件下使用 */
	private static String NAME_SPACE = "http://schemas.android.com/apk/res/android";
	private Button button = null;
	private View loadingView = null;
	private TextView loadingText = null;

	private String buttonTxt = null;
	private OnClickListener listener = null;

	public LoadButton(Context context, AttributeSet attrs) {
		super(context, attrs);
		View v = View.inflate(getContext(), R.layout.load_button_view, null);
		button = (Button) v.findViewById(R.id.button);
		button.setOnClickListener(this);
		loadingView = v.findViewById(R.id.loading);
		loadingText = (TextView) v.findViewById(R.id.loading_txt);
		int buttonText = attrs.getAttributeResourceValue(NAME_SPACE, "text", 0);
		if (buttonText != 0) {
			setButtonText(buttonText);
		} else {
			setButtonText(attrs.getAttributeValue(NAME_SPACE, "text"));
		}
		int loadingText = attrs.getAttributeResourceValue(null, "loading_text", 0);
		if (loadingText != 0) {
			setLoadingText(loadingText);
		} else {
			setLoadingText(attrs.getAttributeValue(null, "loading_text"));
		}
		addView(v);
	}

	public void setButtonText(String txt) {
		buttonTxt = txt;
		button.setText(txt);
	}

	public void setButtonText(int resId) {
		setButtonText(getContext().getString(resId));
	}

	public void setLoadingText(String txt) {
		loadingText.setText(txt);
	}

	public void setLoadingText(int resId) {
		loadingText.setText(resId);
	}

	public void setLoading(boolean loading) {
		if (loading) {
			button.setText("");
			button.setEnabled(false);
			loadingView.setVisibility(View.VISIBLE);
		} else {
			setButtonText(buttonTxt);
			button.setEnabled(true);
			loadingView.setVisibility(View.GONE);
		}
	}

	@Override
	public void setEnabled(boolean enabled) {
		super.setEnabled(enabled);
		button.setEnabled(enabled);
	}

	@Override
	public void setOnClickListener(OnClickListener l) {
		listener = l;
	}

	@Override
	public void onClick(View v) {
		if (v == button && listener != null) {
			listener.onClick(this);
		}
	}

}
